<template>
  <div class="center_management_wrapper">
    <!-- 💭主要页面 -->
    <div class="main_page">
      <div class="search_part">
        <el-button type="primary" size="mini" @click="handleSave()">保存</el-button>
        <el-button size="mini" @click="handleBatchRelevance()">批量关联</el-button>
      </div>
      <div class="table_part">
        <!-- 表格 -->
        <el-table :data="tableData" :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }" :stripe="true">
          <el-table-column fixed align="center" label="中心编号" prop="coreCode"></el-table-column>
          <el-table-column fixed align="center" label="中心名称" prop="coreName"></el-table-column>
          <!-- 动态列部分 -->
          <el-table-column
            v-for="item in ChangedTableStructure"
            :key="item.dataIndex"
            :label="item.title"
            :prop="item.dataIndex"
            width="150"
          >
            <template v-slot="{ row }">
              <div v-if="item.dataIndex" :class="{ grey_font: row[item.dataIndex].originChecked }">
                <!-- 单选框 -->
                <el-checkbox
                  @change="handelCellCheckChange($event, row)"
                  v-model="row[item.dataIndex].checked"
                  style="margin-right: 4px"
                  :disabled="row[item.dataIndex].checkDisabled"
                ></el-checkbox>
                <!-- 版本 -->
                <span>{{ row[item.dataIndex].childVersion }}</span>
                <!-- 数据库编号 -->
                <span v-if="row[item.dataIndex].originChecked">({{ row[item.dataIndex].databaseNum }})</span>
                <!-- 生效时间 -->
                <span v-if="row[item.dataIndex].originChecked">({{ row[item.dataIndex].effectTime }})</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-row type="flex" justify="end" style="margin-top: 24px">
          <el-pagination
            @size-change="handleSizeChange($event)"
            @current-change="handleCurrentChange($event)"
            :current-page="pageParams.pageNo"
            :page-size="pageParams.pageSize"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </el-row>
      </div>
    </div>
    <!-- 💭批量关联弹窗部分 -->
    <el-dialog title="批量关联中心" :visible="relevancyDiaVis" @close="handleRelevancyDiaCancel()" width="600px">
      <el-form ref="relevancyFormRef" :model="relevancyData" :rules="formRules" label-width="120px">
        <el-form-item label="目标版本：" prop="databaseVersionId">
          <el-select
            @change="handelTargetVersionChange"
            v-model="relevancyData.databaseVersionId"
            size="mini"
            style="width: 80%"
          >
            <el-option
              v-for="item in targetVersionOptions"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="中心名称：" prop="coreIds">
          <el-select
            :disabled="coreNameDisabled"
            multiple
            v-model="relevancyData.coreIds"
            size="mini"
            style="width: 80%"
          >
            <el-option
              v-for="item in coreNameOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
          <el-button type="primary" size="mini" @click="handleCoreNameSelectAll">全选</el-button>
        </el-form-item>
        <el-form-item label="生效时间：" prop="effectTime">
          <el-date-picker
            v-model="relevancyData.effectTime"
            size="mini"
            style="width: 80%"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleRelevancyDiaCancel()" size="mini">取 消</el-button>
        <el-button type="primary" @click="handleRelevancyDiaConfirm()" size="mini">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 💭保存弹窗 -->
    <el-dialog title="保存" :visible="saveDiaVis" @close="handleSaveDiaCancel()" width="600px">
      <el-form ref="saveFormRef" :model="saveFormData" label-width="120px" :rules="saveRules">
        <el-form-item label="生效时间：" prop="effectTime">
          <el-date-picker
            v-model="saveFormData.effectTime"
            size="mini"
            style="width: 80%"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleSaveDiaCancel()" size="mini">取 消</el-button>
        <el-button type="primary" @click="handleSaveDiaConfirm()" size="mini">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { cloneDeep } from 'lodash-es'
export default {
  data() {
    return {
      relevancyDiaVis: false,
      pageParams: {
        pageNo: 1,
        pageSize: 10,
      },
      saveRules: {
        effectTime: [
          {
            required: true,
            message: '请选择',
            trigger: 'blur',
          },
        ],
      },
      total: null,
      projectId: '',
      projectDatabaseId: '',
      ChangedTableStructure: [],
      tableData: [],
      relevancyData: {
        databaseVersionId: '',
        coreIds: [],
        effectTime: '',
      },
      saveFormData: {
        effectTime: '',
        cores: [],
      },
      saveDiaVis: false,
      // 数据1
      dataOne: '',
      // 数据2
      dataTwo: '',
      // 数据3
      dataThree: '',
      // 原始表格数据
      originTableData: [],
      // 目标版本下拉项
      targetVersionOptions: [],
      // 中心名称是否能选
      coreNameDisabled: true,
      // 中心名称下拉项
      coreNameOptions: [],
      // 是否能打开保存框
      openSave: false,
      formRules: {
        databaseVersionId: [
          {
            required: true,
            message: '请选择',
            trigger: 'blur',
          },
        ],
        coreIds: [
          {
            required: true,
            message: '请选择',
            trigger: 'blur',
          },
        ],
        effectTime: [
          {
            required: true,
            message: '请填写',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  created() {
    this.projectId = localStorage.getItem('sys-project-id') || ''
    this.projectDatabaseId = localStorage.getItem('project-database-Id') || ''
    this.handleData()
  },
  methods: {
    ...mapActions('centralManagement', [
      'getCoreDatabaseVersionListAPI',
      'getDatabaseVersionListAPI',
      'getDatabaseVersionCoreTableAPI',
      'batchInsertCoreDatabaseAPI',
    ]),
    // 1. 获取表格数据
    async getTableData() {
      const params = {
        projectId: this.projectId,
        projectDatabaseId: this.projectDatabaseId,
        ...this.pageParams,
      }
      const res = await this.getCoreDatabaseVersionListAPI({ params })
      this.total = res.data.total
      this.dataOne = res.data.records
    },
    // 2. 获取目标版本列表
    async getTargetVersionListData() {
      const params = {
        projectId: this.projectId,
        projectDatabaseId: this.projectDatabaseId,
      }
      const res = await this.getDatabaseVersionListAPI({ params })
      this.dataTwo = res.data
    },
    // 3. 获取表结构
    async getListStructure() {
      const params = {
        projectId: this.projectId,
        projectDatabaseId: this.projectDatabaseId,
      }
      const res = await this.getDatabaseVersionCoreTableAPI({ params })
      this.dataThree = res.data.reverse()
    },
    // 数据三个接口的数据处理
    async handleData() {
      this.ChangedTableStructure = []
      await Promise.all([this.getTableData(), this.getTargetVersionListData(), this.getListStructure()])
      // 1. 补齐表头
      this.dataThree.forEach(item => {
        this.ChangedTableStructure.push({
          title: item.databaseVersion + '(' + item.createTime + ')',
          dataIndex: item.childId,
        })
        // 给dataOne补齐属性
        if (item.childId) {
          this.dataOne.forEach(it => {
            it[item.childId] = ''
          })
        }
      })
      // 2. 设置表格数据
      // 给dataTwo添加唯一的childId id即使childId
      // 给dataOne动态部分添加上初始的数据
      this.dataOne.forEach(item => {
        this.dataThree.forEach(it => {
          if (it.childId) {
            item[it.childId] = {
              childVersion: it.childVersion,
              checked: false,
              checkDisabled: false,
            }
          }
        })
      })
      // 动态部分需要补齐的进行一个补齐
      this.dataOne.forEach(item => {
        // 循环该条数据
        for (const k in item) {
          // 循环数据里面得versionTimeVOList
          item.versionTimeVOList.forEach(it => {
            if (k === it.id) {
              item[k].effectTime = it.effectTime
              item[k].checked = true
              item[k].originChecked = true
              item[k].checkDisabled = true
            } else {
            }
          })
          // 循环dataTwo
          this.dataTwo.forEach(ite => {
            if (k === ite.id) {
              item[k].databaseNum = ite.databaseNum
            }
          })
        }
      })
      this.tableData = cloneDeep(this.dataOne)
      this.tableData.sort((a, b) => a.coreCode - b.coreCode)
      this.originTableData = cloneDeep(this.dataOne)
      // 3. 设置批量关联弹窗的目标版本下拉项
      this.targetVersionOptions = this.dataTwo.map(item => ({
        label: item.useVersion + '(' + item.databaseNum + ')',
        value: item.id,
        databaseId: item.databaseId,
      }))
    },
    // 点击批量关联
    handleBatchRelevance() {
      this.relevancyDiaVis = true
    },
    // 选择目标版本
    handelTargetVersionChange(val) {
      // 找到有版本被关联的databaseId
      // 循环动态表头，找到版本id下的关联的中心
      const obj = {}
      this.ChangedTableStructure.forEach(item => {
        const itemArr = []
        this.dataOne.forEach(it => {
          if (it[item.dataIndex].originChecked) {
            itemArr.push(it.id)
          }
        })
        obj[item.dataIndex] = itemArr
      })
      // 将版本id转换成databaseId
      const objTwo = {}
      for (let k in obj) {
        const findObj = this.targetVersionOptions.find(it => it.value === k)
        objTwo[findObj.databaseId] = obj[k]
      }
      // 找到选择的版本的databaseId
      const currentDatabaseId = this.targetVersionOptions.find(item => item.value === val).databaseId

      const arr = objTwo[currentDatabaseId]

      this.coreNameOptions = this.dataOne.map(item => {
        if (arr.includes(item.id)) {
          return {
            label: item.coreName,
            value: item.id,
            disabled: true,
          }
        } else {
          return {
            label: item.coreName,
            value: item.id,
            disabled: false,
          }
        }
      })
      // 取消中心名换的禁选
      this.coreNameDisabled = false
      //  清空中心名称的选择
      this.relevancyData.coreIds = []
      this
    },
    // 中心名称点击全选
    handleCoreNameSelectAll() {
      let length = 0
      this.coreNameOptions.forEach(item => {
        if (!item.disabled) {
          length = length + 1
        }
      })
      if (this.relevancyData.coreIds.length !== length) {
        this.relevancyData.coreIds = []
        this.coreNameOptions.forEach(item => {
          if (!item.disabled) this.relevancyData.coreIds.push(item.value)
        })
      }
    },
    // 点击保存
    handleSave() {
      if (this.openSave) {
        this.saveDiaVis = true
      } else {
        this.$message.warning('尚未勾选版本！')
      }
    },
    // 页码改变
    handleCurrentChange(val) {
      this.pageParams.pageNo = val
      this.handleData()
    },
    // 页码尺寸改变
    handleSizeChange(val) {
      this.pageParams.pageSize = val
      this.handleData()
    },
    // 批量关联公共关闭
    publicCloseRelevancyDia() {
      this.$refs.relevancyFormRef.resetFields()
      this.relevancyData.databaseVersionId = ''
      this.relevancyData.coreIds = ''
      this.relevancyData.effectTime = ''
      this.relevancyDiaVis = false
    },
    // 批量关联弹窗取消
    handleRelevancyDiaCancel() {
      this.publicCloseRelevancyDia()
    },
    // 批量关联弹窗确认
    async handleRelevancyDiaConfirm() {
      await this.$refs.relevancyFormRef.validate()
      const data = {
        projectId: this.projectId,
        projectDatabaseId: this.projectDatabaseId,
        ...this.relevancyData,
      }

      data.cores = data.coreIds.map(item => {
        return {
          databaseVersionId: data.databaseVersionId,
          coreId: item,
        }
      })
      const res = await this.batchInsertCoreDatabaseAPI({ data })
      if (res.code === 200) {
        this.$message.success('批量关联成功！')
        this.handleData()
        this.publicCloseRelevancyDia()
      }
    },
    // 保存公共关闭
    publicCloseSaveDia() {
      this.$refs.saveFormRef.resetFields()
      this.saveFormData.effectTime = ''
      this.saveDiaVis = false
    },
    // 点击单元格的单选按钮
    handelCellCheckChange(val, row) {
      // 当前所有的数据库名字，用作后面的遍历
      const dataBaseArr = []
      this.dataThree.forEach(item => {
        if (item.childId) {
          dataBaseArr.push(item.childId)
        }
      })

      if (val) {
        // 选中
        const index = this.originTableData.findIndex(item => item.coreCode === row.coreCode)
        dataBaseArr.forEach(it => {
          if (row[it].checked !== this.originTableData[index][it].checked) {
            // 保存选中的数据
            this.saveFormData.cores.push({
              coreId: row.id,
              databaseVersionId: it,
            })
          } else {
            row[it].checkDisabled = true
          }
        })
      } else {
        // 取消选中
        const index = this.originTableData.findIndex(item => item.coreCode === row.coreCode)
        dataBaseArr.forEach(it => {
          if (row[it].checkDisabled !== this.originTableData[index][it].checkDisabled) {
            row[it].checkDisabled = false
          }
        })
        this.saveFormData.cores = this.saveFormData.cores.filter(item => item.coreId !== row.id)
      }
      if (this.saveFormData.cores.length === 0) {
        this.openSave = false
      } else {
        this.openSave = true
      }
    },
    // 保存弹窗确认
    async handleSaveDiaConfirm() {
      await this.$refs.saveFormRef.validate()
      const data = {
        projectId: this.projectId,
        projectDatabaseId: this.projectDatabaseId,
        ...this.saveFormData,
      }
      const res = await this.batchInsertCoreDatabaseAPI({ data })
      if (res.code === 200) {
        this.$message.success('保存成功！')
        this.handleData()
        this.publicCloseSaveDia()
        this.openSave = false
      }
    },
    // 保存弹窗取消
    async handleSaveDiaCancel() {
      this.publicCloseSaveDia()
    },
  },
}
</script>

<style lang="scss" scoped>
.center_management_wrapper {
  background-color: $white;
  height: 100%;
  .main_page {
    background-color: $white;
    padding: 12px;
    .table_part {
      margin-top: 24px;
      .grey_font {
        color: #c0c4cc;
      }
    }
  }
}
</style>
